<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChCustomerService;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Config\Annotation\Value;
use Mine\Abstracts\AbstractMapper;

class ChCustomerServiceMapper extends AbstractMapper
{
    #[Value('cache.default.prefix')]
    protected string $prefix;


    public function assignModel()
    {
        $this->model = ChCustomerService::class;
    }


    #[Cacheable('ch_customer_service_info',value: "#{id}",ttl: 15 * 60)]
    public function findById(mixed $id): ChCustomerService|\Hyperf\Database\Model\Model|string|\Hyperf\Database\Model\Builder|null
    {
        return $this->model::query()
            ->where('id',$id)
            ->first();
    }

    public function checkAccount(string $account, mixed $id = ''): bool
    {
        return $this->model::query()
            ->when(!empty($id),function ($query) use ($id){
                $query->where('id','<>',$id);
            })
            ->where('account',$account)
            ->exists();
    }

    public function findByAccount(string $account): array
    {
        $userInfo = $this->model::query()->where('account', $account)->first();
        return empty($userInfo) ? [] : $userInfo->toArray();
    }

    /**
     * 检查用户密码
     */
    public function checkPass(string $password, string $hash): bool
    {
        return $this->model::passwordVerify($password, $hash);
    }

    public function clearCache(mixed $id): void
    {
        $redis = redis();
        $keyOne = $this->prefix . 'ch_customer_service_info:' . $id;
        $redis->del([$keyOne]);
    }

    public function findByIds(array $ids)
    {
        if (!empty($ids)) {
            return $this->model::query()
                ->whereIn('id', $ids)
                ->orderByRaw('sort')
                ->get()
                ->toArray();
        }
        return [];
    }
}